#Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.
#
#This file is part of the Mnova scripting toolkit.
#
#Authorized users of Mnova Software may use this file freely, but this file is provided AS IS
#with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
#FOR A PARTICULAR PURPOSE.

import urllib.request
import sys
import base64

if len(sys.argv) < 4:
	sys.exit("Wrong number of parameters passed")

aURL = sys.argv[1]
aAction = sys.argv[2]
aResponseFile = sys.argv[3]


try:
	req = urllib.request.Request(url = aURL, data = aAction.encode('UTF-8'))

	if len(sys.argv) > 4:
		aLogin = sys.argv[4]
		aPassword = sys.argv[5]
		userAndPass = aLogin + ":" + aPassword
		encodedstring = base64.encodestring(userAndPass.encode('ascii'))[:-1]
		authheader = "Basic %s" % encodedstring.decode('utf-8')
		req.add_header("Authorization", authheader)

	resp = urllib.request.urlopen(req)
	content = resp.read()
	with open(aResponseFile, 'wb') as respFile:
		respFile.write(content)
except Exception as e:
	sys.exit(e)